<template>
    <section class='part-1'>
        <TopHeader></TopHeader>
        <div class='chart-part'>
            <section class='aside-chart'>
                <div class='small-chart'>
                    <XGlassBox>
                        <template #title>
                            <div class='color-f5f5f5'>设备告警类型统计<span class='f-14'>（单位：次）</span></div>
                        </template>

                        <template #link>
                            <a href='/admin/#/device/fireDevice'>详情</a>
                        </template>

                        <div class='chart-body'>
                            <div class='padding-left-28'>
                                <XRadioOptions :options='dateRange' v-model='dateRangeType.deviceWarnType' @change="getDeviceWarnTypeStatisticsData"></XRadioOptions>
                            </div>
                            
                            <div class='DeviceWarnTypeStatisticsChart' style='flex:1;'>
                                <DeviceWarnTypeStatisticsChart v-model='DeviceWarnTypeStatisticsData'></DeviceWarnTypeStatisticsChart>
                            </div>
                        </div>
                    </XGlassBox>
                </div>
                <div class='big-chart'>
                    <XGlassBox>
                        <template #title>
                            <div class='color-f5f5f5'>告警类型比</div>
                        </template>

                        <div class='chart-body'>
                            <div class='padding-left-28'>
                                <XRadioOptions :options='dateRange' v-model='dateRangeType.deviceWarnTypeRate' @change="getDeviceWarnTypeRateData"></XRadioOptions>
                            </div>
                            
                            <div class='DeviceWarnTypeRateChart' style='flex:1;'>
                                <DeviceWarnTypeRateChart v-model='DeviceWarnTypeRateData'></DeviceWarnTypeRateChart>
                            </div>
                            <div class='DeviceWarnTypeRateChartItemName'>
                                <template v-for='(item, index) in DeviceWarnTypeRateData' :key='index'>
                                    <XColorBlockText type='square' :color='deviceWarnTypeRateColor[index]' :class='{"m-l-15" : index > 0}'>{{item.name}}</XColorBlockText>
                                </template>
                            </div>
                        </div>
                        
                    </XGlassBox>
                </div>
            </section>




            <section class='map-part'>
                <div class='warn-total-overview'>
                    <div class='item'>
                        <div class='name'>今日设备告警</div>
                        <div class='value'>{{warnTotalOverview.deviceAlert}}</div>
                    </div>
                    <div class='item'>
                        <div class='name'>今日消防报警</div>
                        <div class='value'>{{warnTotalOverview.fireAlert}}</div>
                    </div>
                    <div class='item'>
                        <div class='name'>消防设备总数</div>
                        <div class='value'>{{warnTotalOverview.fireDeviceTotalNum}}</div>
                    </div>
                    <div class='item'>
                        <div class='name'>充电设备总数</div>
                        <div class='value'>{{warnTotalOverview.deviceTotalNum}}</div>
                    </div>
                </div>


                <div style='flex:1;position:relative'>
                    <Map v-model='mapWarnData' @mouseover='mouseoverMap'></Map>
                    <!-- <Map v-model='mapWarnData' @mouseover='mouseoverMap'></Map> -->
                    <div class='map-message-show'>
                        <div class='message'>
                            <template v-for='(item, index) in warnMessageList' :key='index'>
                                <div class='item'>
                                    <div class='content'>
                                        {{item.time}}
                                        <span class='m-l-15'>{{item.message}}</span>
                                    </div>
                                    <div class='device'>设备编号：<span class='f-18'>{{item.deviceNo}}</span></div>
                                </div>
                            </template>
                        </div>
                        <div class='legend'>
                            <template v-for='(color, key) in FIRE_WARN_COLORS' :key='key'>
                                <div class='item'><XColorBlockText type='square' :color='color'>{{FIRE_WARN_NAMES[key]}}</XColorBlockText></div>
                            </template>
                        </div>
                    </div>
                    
                </div>


            </section>



            <section class='aside-chart'>
                <div class='small-chart'>
                    <XGlassBox>
                        <template #title>
                            <div class='color-f5f5f5'>消防预警总榜(top5)</div>
                        </template>

                        <div class='chart-body'>
                            <div class='padding-left-28'>
                                <XRadioOptions :options='dateRange' @change='warnTotalRank' v-model='dateRangeType.totalTop5'></XRadioOptions>
                            </div>
                            
                            <div class='FireWarnTop5-part' style='flex:1;'>
                                <div class='chart'>
                                    <div class='wrap'>
                                        <div class='FireWarnTop5'>
                                            <FireWarnTop5Chart :colors='fireColors' v-model='FireWarnTop5Data'></FireWarnTop5Chart>
                                        </div>
                                    </div>
                                </div>
                                <div class='legend'>
                                    <div>
                                        <template v-for='(item, index) in FireWarnTop5Data' :key='index'>
                                            <div :class='{"m-t-15" : index > 0}'><XColorBlockText type='square' :color='item.color'>{{item.name}}</XColorBlockText></div>
                                        </template>
                                    </div>
                                    <div class='num'>
                                        <template v-for='(item, index) in FireWarnTop5Data' :key='index'>
                                            <div class='f-16 color-fff' :class='{"m-t-15" : index > 0}'>{{item.value}}</div>
                                        </template>
                                    </div>
                                    <div class='num'>
                                        <template v-for='(item, index) in FireWarnTop5Data' :key='index'>
                                            <div class='f-16 color-fff' :class='{"m-t-15" : index > 0}'>{{item.percent}}%</div>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                    </XGlassBox>
                </div>


                <div class='big-chart'>
                    <XGlassBox>
                        <template #title>
                            <div class='color-f5f5f5'>消防预警省份排名(top5)</div>
                        </template>

                        <div class='chart-body'>
                            <div class='padding-left-28'>
                                <XRadioOptions :options='dateRange' @change='warnProvinceRank' v-model='dateRangeType.provinceTop5'></XRadioOptions>
                            </div>
                            
                            <div class='FireWarnProvinceTop5Chart' style='flex:1;'>
                                <FireWarnProvinceTop5Chart v-model='FireWarnProvinceTop5Data'></FireWarnProvinceTop5Chart>
                            </div>
                        </div>
                        
                    </XGlassBox>
                </div>

            </section>
        </div>
    </section>




    <section id='monitor-data' class='part-2'>
        <div class='data-table'>
            <XGlassBox :cwRate='0.15'>
                <template #title>
                    <div class='color-f5f5f5'>消防设备详情</div>
                </template>

                <div class='m-t-20 padding-left-28 overflow'>
                    <div class='pull-left'>
                        <a-form :model='filterParams' layout='inline'>
                            <a-form-item label='设备编号'>
                                <a-input class='input-field' v-model:value='filterParams.deviceNo'/>
                            </a-form-item>
                            <a-form-item class='m-l-20' label='设备类型'>
                                <a-select class='input-select m-l-10' allowClear v-model:value='filterParams.deviceType'>
                                    <template v-for='(item, key) in DEVICE_TYPE' :key='key'>
                                        <a-select-option :value='key'>{{item}}</a-select-option>
                                    </template>
                                </a-select>
                            </a-form-item>
                            <a-form-item class='m-l-20' label='报警状态'>
                                <a-select class='input-select m-l-10' allowClear v-model:value='filterParams.alertStatus'>
                                    <template v-for='(item, key) in {0 : "正常", 1 : "异常"}' :key='key'>
                                        <a-select-option :value='key'>{{item}}</a-select-option>
                                    </template>
                                </a-select>
                            </a-form-item>
                            <a-form-item class='m-l-20' label='设备状态'>
                                <a-select class='input-select m-l-10' allowClear v-model:value='filterParams.status'>
                                    <template v-for='(item, key) in {0 : "离线", 1 : "在线", 2 : "禁用"}' :key='key'>
                                        <a-select-option :value='key'>{{item}}</a-select-option>
                                    </template>
                                </a-select>
                            </a-form-item>
                            <a-form-item class='m-l-20'>
                                <a-button type="primary" @click='search'>查询</a-button>
                            </a-form-item>
                        </a-form>
                    </div>
                    <div class='pull-right padding-right-28'>
                        <a-button :loading='exportLoading' ghost @click='exportFireDeviceList'>导出EXCEL</a-button>
                    </div>
                </div>


                <div class='m-t-20'>
                    <table class='table'>
                        <thead>
                            <tr>
                                <th class='text-center'>设备编号</th>
                                <th class='text-center'>设备类型</th>
                                <th class='text-center'>安装位置</th>
                                <th class='text-center'>关联充电设备</th>
                                <th class='text-center'>报警联系人</th>
                                <th class='text-center'>最近一次上报值</th>
                                <th class='text-center'>报警状态</th>
                                <th class='text-center'>设备状态</th>
                                <th class='text-center'>查看监控</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template v-for='(item, index) in fireDeviceDataList' :key='index'>
                                <tr>
                                    <td class='text-center'>{{item.deviceNo}}</td>
                                    <td align='center'>{{item.deviceTypeStr}}</td>
                                    <td align='center'>{{item.address}}</td>
                                    <td align='center'>
                                        <template v-for='(v, i) in item.matchDeviceNoList' :key='i'>
                                            <div style='white-space: nowrap;'>{{v.deviceTypeStr}} {{v.deviceNo}}</div>
                                        </template>
                                    </td>
                                    <td align='center'>
                                        <div style='white-space: nowrap;' v-if='item.warnContactName1'>{{item.warnContactName1}}/{{item.warnContactTel1}}</div>
                                        <div style='white-space: nowrap;' v-if='item.warnContactName2'>{{item.warnContactName2}}/{{item.warnContactTel2}}</div>
                                        <div style='white-space: nowrap;' v-if='item.warnContactName3'>{{item.warnContactName3}}/{{item.warnContactTel3}}</div>
                                    </td>
                                    <td align='center'>
                                        <template v-if='item.latelyAlertArr'>
                                            <template v-for='(v, i) in item.latelyAlertArr' :key='i'>
                                                <div style='white-space: nowrap;'>{{v}}</div>
                                            </template>
                                        </template>
                                    </td>
                                    <td align='center'>{{item.alertStatusStr}}</td>
                                    <td align='center'>{{item.statusStr}}</td>
                                    <td align='center'>
                                        <a style='color:#d7621c' target="_blank" :href='item.monitorUrl'>查看</a>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                    <div class='m-t-20' style='text-align:right;padding-right:20px'>
                        <XPagination ref='fireDeviceDataListRef' :queryParams='queryParams' :showSizeChanger='false' :load='fireDeviceListPagination' @finish='fireDeviceDataList = $event'></XPagination>
                    </div>
                </div>

                

            </XGlassBox>
        </div>
    </section>

    <div v-show='modalVisible' class='modal-dialog' ref='modalDialogRef' :style='{left : modalDialogLeft + "px", top : modalDialogTop + "px"}'>
        <ModalDialog v-if='modalVisible' v-model:data='modalWarnData' :colors='fireColors'></ModalDialog>
    </div>

    <div class='ling' @click='toggleLing'>
        <template v-if='isOpenLing'>
            <img src='@/assets/images/ling.png' />
        </template>
        <template v-else>
            <img src='@/assets/images/no-ling.png' />
        </template>
        
        <audio webkit-playsinline="" x-webkit-airplay="" preload="auto" ref='lingRef' src='https://downsc.chinaz.net/Files/DownLoad/sound1/202104/14184.wav'></audio>
    </div>

</template>

<script lang="ts">
import { defineComponent, nextTick, onMounted, reactive, ref, toRefs } from 'vue'
import XGlassBox from '../../components/GlassBox'
import XRadioOptions from '../../components/RadioOptions'
import TopHeader from './TopHeader.vue'

import * as API from '../../service/Api'

import { FIREColors } from './Colors'
const fireColors:FIREColors = {
    '水浸报警' : '#1cb2ff',
    '烟雾报警' : '#be85ff',
    '高温报警' : '#eb3d3f',
    '高温预警' : '#ff9c1c'
}


import { FIRE_WARN_COLORS, FIRE_WARN_NAMES, DEVICE_TYPE } from '../../config'

import DeviceWarnTypeStatisticsChart from './charts/DeviceWarnTypeStatisticsChart.vue'
import DeviceWarnTypeRateChart from './charts/DeviceWarnTypeRateChart.vue'
import FireWarnTop5Chart from './charts/FireWarnTop5Chart.vue'
import FireWarnProvinceTop5Chart from './charts/FireWarnProvinceTop5Chart.vue'
import Map from './charts/Map.vue'
import ModalDialog from './ModalDialog.vue'

interface TableData {
    filterParams : {[key:string]:any};
    fireDeviceDataListRef : any;
    queryParams : {[key:string]:any};
    fireDeviceDataList : any[];
    exportLoading : boolean;
    fireDeviceListPagination:any;
    [key:string]:any;
}


export default defineComponent({
    components : {
        TopHeader,
        XGlassBox,
        XRadioOptions,

        DeviceWarnTypeStatisticsChart,
        DeviceWarnTypeRateChart,

        FireWarnTop5Chart,
        FireWarnProvinceTop5Chart,

        Map,
        ModalDialog
    },

    setup() {
        const deviceWarnTypeRateColor = ref(['#1b8fff', '#7233ff', '#53cb1a', '#ef485f'])

        let lingRef = ref(null)
        let isOpenLing = ref(false)

        const dateRangeType = reactive({
            deviceWarnType : 1,
            deviceWarnTypeRate : 1,
            totalTop5 : 1,
            provinceTop5 : 1,
        })
        const deviceWarnType = ref(1)
        const dateRange = reactive ([{value : 1, label : '当日'}, {value : 2, label : '7日'}, {value : 3, label : '30日'}])

        let DeviceWarnTypeStatisticsData = ref<any[]|null>(null)
        let DeviceWarnTypeRateData = ref<any[]|null>(null)

        let FireWarnTop5Data = reactive([]) //总榜
        let FireWarnProvinceTop5Data = ref<any>(null) //省排行



        let warnTotalOverview = ref({ //总数预览
            deviceAlert: 0,
            deviceTotalNum: 0,
            fireAlert: 0,
            fireDeviceTotalNum: 0
        })


        let state = reactive({
            modalDialogRef : null,
            modalDialogLeft : 0,
            modalDialogTop : 0,
            modalVisible : false,

            mapWarnData : [],
            modalWarnData : {},



            warnMessageList : []

            
        })

        let tableData = reactive<TableData>({
            fireDeviceDataListRef : null,
            filterParams : {

            },
            queryParams : {

            },

            fireDeviceDataList : [],

            exportLoading : false,

            fireDeviceListPagination : API.fireDeviceListPagination
        })



        async function getDeviceWarnTypeStatisticsData() {
            DeviceWarnTypeStatisticsData.value = null
            let data = await API.deviceWarnTypeStatisticsData(dateRangeType.deviceWarnType as any)
            if(data) {
               DeviceWarnTypeStatisticsData.value = [...data.map(item => ({name : item.alarmStr, value : item.num, alarmCode : item.alarmCode}))]
            }else {
                DeviceWarnTypeStatisticsData.value
            }
        }

        async function getDeviceWarnTypeRateData() {
             DeviceWarnTypeRateData.value = null
            let data = await API.deviceWarnTypeStatisticsData(dateRangeType.deviceWarnTypeRate as any)
            if(data) {
               DeviceWarnTypeRateData.value = [...data.map(item => ({name : item.alarmStr, value : item.num, percent : item.percent, alarmCode : item.alarmCode}))]
            }else {
                DeviceWarnTypeRateData.value = []
            }
        }


        async function getMapWarnData() {
            let data = await API.mapWarnData()
            if(data) {
                state.mapWarnData = data
            }
        }


        async function warnTotalRank() {
            let colors = ['#ff9c1c', '#eb3d3f', '#be85ff', '#1cb2ff', '#a71cff']
            FireWarnTop5Data.splice(0)
            let data = await API.warnTotalRank(dateRangeType.totalTop5 as any)
            if(data) {
                data.sort(function(a:any, b:any){
                    b.num - a.num
                })
                FireWarnTop5Data.push(...data.map((item:any, index:number) => {
                    return {name : item.alarmStr, value : item.num, rate : item.percent / 100, percent : item.percent, alarmCode : item.alarmCode, color : colors[index]}
                }))
            }
        }

        async function warnProvinceRank() {
            FireWarnProvinceTop5Data.value = null
            let data = await API.warnProvinceRank(dateRangeType.provinceTop5 as any)
            if(data) {
                let fireWarnProvinceTop5Data = {
                    area : [],
                    data : []
                }

                data.forEach((item:any) => {
                    fireWarnProvinceTop5Data.area.push(item.name)
                    fireWarnProvinceTop5Data.data.push(item.num)
                })
                

                FireWarnProvinceTop5Data.value = fireWarnProvinceTop5Data
            }
        }


        async function getWarnTotalOverview() {
            let data = await API.warnTotalOverview()
            if(data) {
                warnTotalOverview.value = data
            }
        }

        async function mouseoverMap (e:any) {
            if(e.value) {
                state.modalWarnData = e.value[2]

                state.modalVisible = true
                await nextTick()
                var WH = document.documentElement.offsetHeight || document.body.offsetHeight
                var H = state.modalDialogRef.offsetHeight
                var clientY = e.clientY


                state.modalDialogLeft = e.clientX - 30
                state.modalDialogTop = clientY - H + 30
                
            }else {
                state.modalVisible = false
            }
            
        }

        function search() {
            tableData.queryParams = {...tableData.filterParams}

            nextTick(() => {
                tableData.fireDeviceDataListRef.pagination(1)
            })
            
        }

        async function exportFireDeviceList() {
            tableData.exportLoading = true
            import('../../vendor/Export2Excel.js').then(({export_json_to_excel}) => {
                API.exportFireDeviceList(tableData.filterParams).then(data => {
                    let header = ['设备编号', '设备类型', '安装位置', '关联充电设备', '报警联系人', '最近一次上报值', '报警状态', '设备状态']
                    let rows = []
                    if(data) {
                        rows = data.map(item => {
                            let row = [item.deviceNo, item.deviceTypeStr, item.address]
                            let relationDevice = []
                            if(item.matchDeviceNoList) {
                                relationDevice.push(...item.matchDeviceNoList.map(device => device.deviceTypeStr + '  ' + device.deviceNo))
                            }

                            row.push(relationDevice.join('\r\n'))
                            
                            let lianxiren = []
                            if(item.warnContactName1) {
                                lianxiren.push(item.warnContactName1 + '/' + item.warnContactTel1)
                            }
                            if(item.warnContactName2) {
                                lianxiren.push(item.warnContactName2 + '/' + item.warnContactTel2)
                            }
                            if(item.warnContactName3) {
                                lianxiren.push(item.warnContactName3 + '/' + item.warnContactTel3)
                            }
                            row.push(lianxiren.join('\r\n'))
                            

                            if(item.latelyAlertArr) {
                                row.push(item.latelyAlertArr.join('\r\n'))
                            }else {
                                row.push('')
                            }

                            

                            row.push(item.alertStatusStr)
                            row.push(item.statusStr)

                            return row

                        })
                    }

                    export_json_to_excel({
                        header,
                        data : rows,
                        filename: '汇总表'
                    })

                    tableData.exportLoading = false
                })
                
            })

        }

        function toggleLing() {
            isOpenLing.value = !isOpenLing.value
        }
		
		function run(){
			getDeviceWarnTypeStatisticsData() //设备告警类型
			getDeviceWarnTypeRateData() //设备告警类型占比
			
			getMapWarnData() //获取地图的
			getWarnTotalOverview()
			
			warnTotalRank()
			warnProvinceRank()
		}

        API.fireAlertListSendInfo()

        
        //开启websocket
        var ws = new WebSocket((location.protocol === 'http:' ? 'ws' : 'wss') + '://' + (location.hostname) + '/websocket/statisticsWebsocket/fireAlertMonitor');
        //var ws = new WebSocket('ws://192.168.1.204:8086/statisticsWebsocket/fireAlertMonitor')
        ws.onopen = function() {

        }

        ws.onmessage = function(res) {
            console.log(res)
            try {
                let data = JSON.parse(res.data)
                let warnMessageList = [...state.warnMessageList]
                if(warnMessageList.length >= 8) {
                    warnMessageList.splice(7, warnMessageList.length - 7)
                }
                warnMessageList.unshift(data)

                state.warnMessageList = warnMessageList

                if(isOpenLing.value) {
                    lingRef.value.play()
                }


            } catch (error) {
                
            }

			
			run()
        }



        return {
            deviceWarnType,
            dateRange,
            dateRangeType,

            getDeviceWarnTypeStatisticsData,
            getDeviceWarnTypeRateData,
            DeviceWarnTypeStatisticsData,
            DeviceWarnTypeRateData,

            FireWarnTop5Data,
            warnTotalRank,
            FireWarnProvinceTop5Data,
            warnProvinceRank,

            fireColors,
            deviceWarnTypeRateColor,


            warnTotalOverview,
            FIRE_WARN_COLORS,
            FIRE_WARN_NAMES,
            DEVICE_TYPE,


            ...toRefs(state),
            mouseoverMap,
            



            ...toRefs(tableData),
            search,
            exportFireDeviceList,

            lingRef,
            toggleLing,
            isOpenLing
        }
    }
})
</script>

<style scoped lang='scss' src='./index.scss'></style>


<style lang='scss'>
    @mixin common {
        background: none;
        border: 1px solid #64779e;
        height: 32px;
        border-radius: 4px;
        color: #f5f5f5;
    }
    #monitor-data {

        .ant-form-item-label > label{
            color: #f5f5f5;
            font-size: 16px;
        }


        .input-field{
            width: 167px;
            @include common;
        }
        

        .input-select{
            width: 137px;
            

            .ant-select-selector{
                @include common;
            }

            .ant-select-arrow{
                color: #64779e;
            }
        }

        .ant-btn-primary{
            background: #64779e;
            border-color: #64779e;
        }

        .ant-btn-background-ghost{
            color: #64779e;
            border-color: #64779e;
        }

        .ant-pagination-prev, .ant-pagination-next, .ant-pagination-jump-prev, .ant-pagination-jump-next,
        .ant-pagination-jump-next ant-pagination-jump-next-custom-icon,
        .anticon anticon-double-right ant-pagination-item-link-icon,
        .ant-pagination-jump-prev .ant-pagination-item-container .ant-pagination-item-ellipsis, .ant-pagination-jump-next .ant-pagination-item-container .ant-pagination-item-ellipsis,
        .ant-pagination-item-link, .ant-pagination-item{
            background: none !important;
            color: #fff !important;

            a{
                color: #fff !important;
            }
        }

        .ant-select-clear{
            color:#fff !important;
            background-color:transparent !important;
        }
    }
</style>